package com.campus.filter;

import com.campus.common.TokenManager;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import static com.campus.common.BusinessConstants.*;
/**
 * @desc:
 *    CharacterEncoding
 *    Authentication: 是否为合法用户
 *
 *
 * @author: Ping
 * @date: 2024/11/6 10:41
 */
@Slf4j
public class TokenFilter implements Filter {
    private String [] excludeUrl = {"/user/login", "/error","/user/register"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    private boolean isExcludeUrl(String url) {
        for (String exclude : excludeUrl) {
            if (url.contains(exclude)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        log.info(" Token filter: request url {}.", request.getRequestURI()) ;
        // 放行验证
        if (isExcludeUrl(request.getRequestURI())) {
            // 放行的方法
            log.info("pass Token Filter.") ;
            filterChain.doFilter(servletRequest, servletResponse);
            return ;
        }
        // 验证用户是否合法用户
        HttpSession session = request.getSession();
        if (session.getAttribute(USER_KEY) == null
                || session.getAttribute(TOKEN_KEY) == null) {
            log.info(" Redirect to: {}", request.getContextPath() + "/error/400") ;
            request.setAttribute("errorMsg", "用户未登录");
            // 转发给ErrorController来处理
            request.getRequestDispatcher("/error/400").forward(request, servletResponse);
            return ;
        }
        // 验证token是否合法
        String clientToken = request.getHeader(TOKEN_KEY);
        log.info("Token filter: request url {} , got token {}.",
                request.getRequestURI(), clientToken);
        if (clientToken == null ||
                (!TokenManager.isValided(session, clientToken))) {
            // token无效
            log.info(" Token filter redirect to: {}", request.getContextPath() + "/error/401") ;
            request.setAttribute("errorMsg", "token无效");
            request.getRequestDispatcher("/error/401").forward(request, servletResponse);
            return ;
        }
        // token有效且合法请求
        log.info("request pass the token filter.") ;
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
